local shigui = fk.CreateSkill {
  name = "3s__shigui",
}

local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["3s__shigui"] = "拭圭",
  [":3s__shigui"] = "出牌阶段，你可令一名角色每个区域内的各一张牌当作一张单目标锦囊牌使用，然后你弃置X张牌（X为底牌缺少的花色数），若补齐底牌花色，此牌额外结算一次；否则你和其各摸两张牌，此技能于此阶段失效。",
  ["#3s__shigui-use"] = "拭圭：选择每个区域内的一张牌，当单目标锦囊牌使用",
  ["#3s__shigui-active"] = "你可选择一名角色，其将每个区域内的各一张牌当作一张单目标锦囊牌使用",
  ["#3s__shigui-touse"] = "拭圭：请选择使用的牌名",
  ["#3s__shigui-discard"] = "拭圭：请弃置%arg张牌",
  ["#shigui-extra"] = "%from 的 %card 额外结算一次",
}

shigui:addEffect("active", {
  anim_type = "support",
  prompt = "#3s__shigui-active",
  max_phase_use_time = 999,
  card_num = 0,
  target_num = 1,
  card_filter = Util.FalseFunc,
  target_filter = function(self, player, to_select, selected)
    return #selected == 0 and not to_select:isAllNude()
  end,
  on_use = function(self, room, effect)
    local target = effect.tos[1]
    local cards = U.askforCardsChosenFromAreas(target, target, "hej", shigui.name, "#3s__shigui-use", "", false)
    if #cards > 0 then
      local all_names = {}
      for _, id in ipairs(Fk:getAllCardIds()) do
        local card = Fk:getCardById(id)
        if card:isCommonTrick() and not card.multiple_targets and not card.is_derived then
          table.insertIfNeed(all_names, card.name)
        end
      end
      room:askToUseVirtualCard(target, {
        name = all_names,
        subcards = cards,
        skill_name = shigui.name,
        prompt = "#3s__shigui-touse",
        cancelable = false,
      })
    end
  end,
})

shigui:addEffect(fk.CardUsing, {
  is_delay_effect = true,
  mute = true,
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(shigui.name) and data.card.skillName == shigui.name
    and data.card.type == Card.TypeTrick
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local cards = room:getSubcardsByRule(data.card, { Card.Processing })
    local suits = {}
    for _, id in ipairs(cards) do
      table.insertIfNeed(suits, Fk:getCardById(id):getSuitString())
    end
    local n = 4 - #suits
    local to_discard = room:askToDiscard(player, {
      min_num = n,
      max_num = n,
      include_equip = true,
      skill_name = shigui.name,
      cancelable = false,
      pattern = ".",
      prompt = "#3s__shigui-discard:::"..n
    })
    if #to_discard > 0 then
      for _, id in ipairs(to_discard) do
        table.insertIfNeed(suits, Fk:getCardById(id):getSuitString())
      end
    end
    if #suits == 4 then
      room:sendLog{
        type = "#shigui-extra",
        from = target.id,
        card = { data.card },
        toast = true,
      }
      data.additionalEffect = (data.additionalEffect or 0) + 1
    else
      room:invalidateSkill(player, shigui.name, "-phase")
      room:drawCards(player, 2, shigui.name)
      if target ~= player then
        room:drawCards(target, 2, shigui.name)
      end
    end
  end,
})

return shigui